package io.huaguoguo.connector.adapter;

import io.huaguoguo.servlet.JerryHttpServletRequest;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http.*;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;

import static cn.hutool.core.util.CharsetUtil.CHARSET_UTF_8;

/**
 * 描述： http兼容组件，用于封装HttpRequest和HttpResponse对象，并转发到servlet容器内部  <br>
 * CreateDate: 2021/11/26 <br>
 *
 * @author huaguoguo
 */
@Slf4j
public class HttpAdapter {


    public HttpResponse process(HttpRequest httpRequest) {
        // 把请求封装成 HttpServletRequest 对象
        HttpServletRequest request = new JerryHttpServletRequest(httpRequest);

        //回复信息给浏览器 [http协议]
        ByteBuf content = Unpooled.copiedBuffer("hello, 我是服务器", CHARSET_UTF_8);
        //构造一个http的相应，即 httpresponse
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain;charset=utf-8");
        response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());
        return response;
    }
}
